const createTaskQueue = (maxLimitLength = 5) => {
    maxLimitLength = maxLimitLength || 5 // 最大并发任务数限制
    let ingCount = 0 // 正在执行的任务数量
    const taskQueue = [] // 排队中的task

    const taskWrapper = (fn) => {
        return (...args) => {
            ingCount++
            return fn(...args).finally(() => {
                ingCount--
                if (taskQueue.length) {
                    const task = taskQueue.shift()
                    task()
                }
            })
        }
    }

    return (fn) => {
        return (...args) => {
            if (ingCount >= maxLimitLength) {
                return new Promise((resolve, reject) => {
                    const taskWrapperWithQueue = () => {
                        taskWrapper(fn)(...args).then(resolve).catch(reject)
                    }
                    taskQueue.push(taskWrapperWithQueue)
                })
            } else {
                return taskWrapper(fn)(...args)
            }
        }
    }
}

function createTask(i) {
    return () => {
        return new Promise((resolve) => {
            setTimeout(() => {
                resolve(i)
            }, 1000)
        })
    }
}

(async () => {
    const taskQueueWrapper = createTaskQueue(3)

    for (let i = 0; i < 20; i++) {
        const task = createTask(i)
        const taskWithQueue = taskQueueWrapper(task)
        taskWithQueue().then(res => console.log(res))
    }
})()
